package com.beidouapp.security.mvc;

import com.beidouapp.common.contant.SecurityContant;
import com.beidouapp.common.enums.RoleGroupType;
import com.beidouapp.domain.pojo.OrganizationAndRole;
import com.beidouapp.domain.pojo.Role;
import com.beidouapp.domain.pojo.RoleGroup;
import com.beidouapp.security.model.ReturnDataInfo;
import com.beidouapp.security.model.SessionUser;
import com.beidouapp.security.model.ui.UIRole;
import com.beidouapp.security.utils.DscpCommUtils;
import com.beidouapp.service.OrganizationAndRoleService;
import com.beidouapp.service.OrganizationService;
import com.beidouapp.service.RoleService;
import net.sf.json.JSONObject;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.*;

@Controller
@RequestMapping(value = "/role")
public class RoleController {
    private static final Logger logger = LoggerFactory.getLogger(RoleController.class);

    @Autowired
    private RoleService roleService;

    @Autowired
    private OrganizationService organizationService;

    @Autowired
    private OrganizationAndRoleService organizationAndRoleService;


    /**
     * 查看角色列表
     *
     * @param session
     * @param request
     * @param offset
     * @param limit
     * @param globalSearch
     * @return
     */
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public
    @ResponseBody
    ReturnDataInfo<Role> listPageRoles(HttpSession session, HttpServletRequest request, @RequestParam(value = "iDisplayStart", required = false, defaultValue = "0") Integer offset, @RequestParam(value = "iDisplayLength", required = false, defaultValue = "10") Integer limit, @RequestParam(value = "globalSearch", required = false, defaultValue = "{}") String globalSearch) {
        try {
            Map paramters = new HashMap();
            if (globalSearch != null) {
                JSONObject jsonObject = JSONObject.fromObject(globalSearch);
                paramters.putAll(jsonObject);
            }
            paramters.putAll(request.getParameterMap());
            if (!DscpCommUtils.isSupperAdmin(session)) {
                SessionUser sessionUser = DscpCommUtils.getSessionUser(session);
                paramters.put("orgId", sessionUser.getOrgId());
            }
            List<Role> roleList = roleService.findPageRoles(paramters, offset, limit);
            long totalCount = roleService.countPageRoles(paramters);
            return ReturnDataInfo.createSuccessfulExecuteResults(roleList, offset, limit, totalCount);
        } catch (Exception ex) {
            logger.error("listPageRoles is failed. because {}", ex.getLocalizedMessage(), ex);
            return ReturnDataInfo.createFailedExecuteResult(ex.getMessage());
        }
    }

    /**
     * 添加页面跳转
     *
     * @return
     */
    @RequestMapping(value = "/page/add", method = RequestMethod.GET)
    public String addRole() {
        return "role/role_add";
    }


    /**
     * 授权页面跳转
     *
     * @return
     */
    @RequestMapping(value = "/page/resources/{roleId}", method = RequestMethod.GET)
    public ModelAndView listResource(@PathVariable Long roleId) {
        ModelAndView view = new ModelAndView();
        view.addObject("roleId", roleId);
        view.setViewName("role/role_resource");
        return view;
    }

    /**
     * 修改页面跳转
     *
     * @return
     */
    @RequestMapping(value = "/page/edit/{roleId}", method = RequestMethod.GET)
    public ModelAndView editRole(HttpSession session, @PathVariable Long roleId) {
        ModelAndView view = new ModelAndView();
        view.addObject("role", roleService.getRoleById(roleId));
        view.setViewName("role/role_edit");
        return view;
    }


    @RequestMapping(value = "/saveOrUpdateRole", method = RequestMethod.POST, headers = "Content-Type=application/json")
    public
    @ResponseBody
    ReturnDataInfo<String> saveOrUpdateRole(HttpSession session, HttpServletRequest request, @RequestBody Role role) {
        try {
            if (role == null) {
                logger.error("insert or update Role is failed. role is null!");
                throw new Exception("数据为空或非法！");
            }

            Long orgId = null;
            // 当前用户的组织
            if (!DscpCommUtils.isSupperAdmin(session)) {
                orgId = DscpCommUtils.getSessionUser(session).getOrgId();
                if (orgId == null) {
                    throw new Exception("您没有权限操作此项！");
                }
            }
            roleService.saveOrUpdateRole(role);
            return ReturnDataInfo.createSuccessfulSingleExecuteResult(null);
        } catch (Exception ex) {
            logger.error("insert or update Role is failed. because {}!", ex.getLocalizedMessage(), ex);
            return ReturnDataInfo.createFailedExecuteResult(ex.getMessage());
        }
    }

    /**
     * 删除角色
     *
     * @param session
     * @param params
     * @return
     */
    @RequestMapping(value = "/delete", method = RequestMethod.POST, headers = "Content-Type=application/json")
    public
    @ResponseBody
    ReturnDataInfo<String> deleteRole(HttpSession session, HttpServletRequest request, @RequestBody Map<String, Object> params) {
        String idsStr = (String) params.get("ids");
        try {
            String[] ids = idsStr.split(SecurityContant.SYMBOL_COMMA);
            if (ids.length > 0) {
                Long[] iis = new Long[ids.length];
                for (int i = 0; i < ids.length; i++) {
                    iis[i] = Long.valueOf(ids[i]);
                }
                roleService.removeRoles(iis);
            }
            return ReturnDataInfo.createSuccessfulSingleExecuteResult(null);
        } catch (Exception ex) {
            logger.error("delete Role id [{}] is failed. because {}!", idsStr, ex.getLocalizedMessage(), ex);
            return ReturnDataInfo.createFailedExecuteResult(ex.getMessage());
        }
    }

    @RequestMapping(value = "/findRoleList", method = RequestMethod.GET)
    public
    @ResponseBody
    ReturnDataInfo<Role> findRoleList(HttpSession session, HttpServletRequest request) {
        try {
            List<Role> roleList = Collections.emptyList();
            String orgStr = request.getParameter("orgId");
            if (DscpCommUtils.isSupperAdmin(session)) {
                if ("".equals(orgStr)) {
                    Role r = new Role();
                    r.setRoleGroupId(RoleGroupType.PLAT_ROLE.getCode());
                    roleList = roleService.findRoleList(r);
                } else {
                    //查询所有角色.
                    roleList = roleService.findRolesByOrgId(Long.valueOf(orgStr));
                }

            } else {
                //根据组织机构查询对应的角色列表.
                roleList = roleService.findRolesByOrgId(Long.valueOf(orgStr));
            }
            return ReturnDataInfo.createSuccessfulExecuteResults(roleList);
        } catch (Exception ex) {
            return ReturnDataInfo.createFailedExecuteResult(ex.getMessage());
        }
    }

    /**
     * 列表页面跳转
     *
     * @return
     */
    @RequestMapping(value = "/page/list", method = RequestMethod.GET)
    public String forward2RolePage() {
        return "role/role";
    }


    @RequestMapping(value = "/listStatus/{orgId}", method = RequestMethod.GET)
    public
    @ResponseBody
    ReturnDataInfo<UIRole> listOrgRoleStatus(HttpSession session, @PathVariable Long orgId) {
        try {
            List<Role> listRoles = null;
            SessionUser su = DscpCommUtils.getSessionUser(session);
            if (DscpCommUtils.isSupperAdmin(session)) {
                listRoles = roleService.findRoleList(new Role());
            } else {
                // 当前用户的组织
                Long root_orgId = su.getOrgId();
                Map<String, Object> params = new HashMap<String, Object>();
                params.put("roleGroupId", su.getRoleGroupId());
                params.put("orgId", su.getOrgId());
                listRoles = roleService.findRolesByMap(params);
            }
            Map<String, Object> params = new HashMap<String, Object>();
            params.put("orgId", orgId);
            List<Role> roles = roleService.findRolesByMap(params);
            List<UIRole> uiRoles = new ArrayList<UIRole>();

            for (Role listRole : listRoles) {
                if (listRole.getRoleGroupId() == RoleGroupType.PLAT_ROLE.getCode()) {
                    continue;
                }
                UIRole uiRole = new UIRole();
                uiRole.setId(listRole.getId());
                uiRole.setCode(listRole.getCode());
                uiRole.setName(listRole.getName());
                uiRole.setDescn(listRole.getDescn());
                for (Role role : roles) {
                    if (listRole.getId().longValue() == role.getId().longValue()) {
                        uiRole.setIsChecked(true);
                        break;
                    }
                }
                uiRoles.add(uiRole);
            }
            return ReturnDataInfo.createSuccessfulExecuteResults(uiRoles);
        } catch (Exception ex) {
            return ReturnDataInfo.createFailedExecuteResult(ex.getMessage());
        }
    }


    @RequestMapping(value = "/grantRoles2Org/{orgId}", method = RequestMethod.POST, headers = "Content-Type=application/json")
    public
    @ResponseBody
    ReturnDataInfo<String> grantRoles(HttpSession session, HttpServletRequest request, @RequestBody List<Long> roles, @PathVariable Long orgId) {
        try {
            if (orgId == null) {
                throw new Exception("机构不能为空！");
            }
            OrganizationAndRole organizationAndRole = new OrganizationAndRole();
            organizationAndRole.setOrgId(orgId);
            organizationAndRoleService.removeEntry(organizationAndRole);
            organizationAndRoleService.addOrganizationAndRoleBatch(orgId, roles);
            return ReturnDataInfo.createSuccessfulSingleExecuteResult(null);
        } catch (Exception ex) {
            logger.error("机构关联角色失败！", ex);
            return ReturnDataInfo.createFailedExecuteResult(ex.getMessage());
        }
    }
}
